package com.huaju.enity;

import java.sql.Timestamp;
import java.util.List;

import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import static org.hibernate.criterion.Example.create;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;


/**
 * A data access object (DAO) providing persistence and search support for
 * Payoutlist entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.huaju.enity.Payoutlist
 * @author MyEclipse Persistence Tools
 */
@Transactional
public class PayoutlistDAO {
	private static final Logger log = LoggerFactory
			.getLogger(PayoutlistDAO.class);
	// property constants
	public static final String PDESC = "pdesc";
	public static final String PMONEY = "pmoney";
	public static final String SUCCESS = "success";

	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	protected void initDao() {
		// do nothing
	}

	public boolean save(Payoutlist transientInstance) {
		log.debug("saving Payoutlist instance");
		try {
			getCurrentSession().save(transientInstance);
			log.debug("save successful");
			return true;
		} catch (RuntimeException re) {
			log.error("save failed", re);
			return false;
		}
	}

	public void saveOrUpdate(Payoutlist transientInstance) {
		log.debug("saving Payoutlist instance");
		try {
			getCurrentSession().saveOrUpdate(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public Double getAllPayoutByUser(Integer aid) {
		log.debug("finding all Payoutlist instances");
		try {
			String queryString = " SELECT Sum(pmoney) FROM payoutlist  where aid ="
					+ aid;
			SQLQuery queryObject = getCurrentSession().createSQLQuery(
					queryString);
			if (queryObject.list() != null) {
				try {
					return Double.parseDouble(queryObject.list().get(0)
							.toString());
				} catch (Exception e) {
					// TODO: handle exception
					return 0.00;
				}

			}
			return 0.00;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public void delete(Payoutlist persistentInstance) {
		log.debug("deleting Payoutlist instance");
		try {
			getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Payoutlist findById(java.lang.Integer id) {
		log.debug("getting Payoutlist instance with id: " + id);
		try {
			Payoutlist instance = (Payoutlist) getCurrentSession().get(
					"com.huaju.enity.Payoutlist", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List<Payoutlist> findByExample(Payoutlist instance) {
		log.debug("finding Payoutlist instance by example");
		try {
			List<Payoutlist> results = (List<Payoutlist>) getCurrentSession()
					.createCriteria("com.huaju.enity.Payoutlist")
					.add(create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Payoutlist instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Payoutlist as model where model."
					+ propertyName + "= ?";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public Integer countAll(String pro, Object value, short type) {
		log.debug("finding all Payoutlist instances");
		try {
			String queryString = "from Payoutlist model where model." + pro
					+ "=? and model.success=?";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			queryObject.setParameter(1, type);
			return queryObject.list().size();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List findByPage(Integer start, Integer size, String pro,
			Object value, short type) {
		log.debug("finding all Payoutlist instances");
		try {
			String queryString = "from Payoutlist model where model." + pro
					+ "=? and model.success=? order by pid desc";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			queryObject.setParameter(1, type);
			queryObject.setMaxResults(size);
			queryObject.setFirstResult(start);

			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List<Payoutlist> findByPdesc(Object pdesc) {
		return findByProperty(PDESC, pdesc);
	}

	public List<Payoutlist> findByPmoney(Object pmoney) {
		return findByProperty(PMONEY, pmoney);
	}

	public List<Payoutlist> findBySuccess(Object success) {
		return findByProperty(SUCCESS, success);
	}

	public List findAll() {
		log.debug("finding all Payoutlist instances");
		try {
			String queryString = "from Payoutlist";
			Query queryObject = getCurrentSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	
	
	public List findTotalAnalysis(Integer comId ,String month) {
		try {
			String queryString = "select count(*),sum(pmoney) from payoutlist where successTime > ?";
			if (comId != null) {
				queryString += " and comId="+ comId;
			}
			SQLQuery queryObject = getCurrentSession().createSQLQuery(
					queryString);
			queryObject.setParameter(0, month);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public Integer countAll(short type) {
		log.debug("finding all Payoutlist instances");
		try {
			String queryString = "from Payoutlist model where model.success=?";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, type);
			return queryObject.list().size();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List findByPage(Integer start, Integer size, short type) {
		log.debug("finding all Payoutlist instances");
		try {
			String queryString = "from Payoutlist where success=?  order by pid desc";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, type);
			queryObject.setMaxResults(size);
			queryObject.setFirstResult(start);

			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Payoutlist merge(Payoutlist detachedInstance) {
		log.debug("merging Payoutlist instance");
		try {
			Payoutlist result = (Payoutlist) getCurrentSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Payoutlist instance) {
		log.debug("attaching dirty Payoutlist instance");
		try {
			getCurrentSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Payoutlist instance) {
		log.debug("attaching clean Payoutlist instance");
		try {
			getCurrentSession().buildLockRequest(LockOptions.NONE).lock(
					instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static PayoutlistDAO getFromApplicationContext(ApplicationContext ctx) {
		return (PayoutlistDAO) ctx.getBean("PayoutlistDAO");
	}

	public Double getAllPayoutByUser(Integer aid, Integer type) {
		log.debug("finding all Payoutlist instances");
		try {
			String queryString = " SELECT Sum(pmoney) FROM payoutlist  where aid =? and success=?";
			SQLQuery queryObject = getCurrentSession().createSQLQuery(
					queryString);
			queryObject.setParameter(0, aid);
			queryObject.setParameter(1, type);
			if (queryObject.list() != null) {
				try {
					return Double.parseDouble(queryObject.list().get(0)
							.toString());
				} catch (Exception e) {
					// TODO: handle exception
					return 0.00;
				}

			}
			return 0.00;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List findApplyItems(String propertyName, Object value) {
		log.debug("finding Payoutlist instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Payoutlist as model where model."
					+ propertyName + "= ? and model.success=0";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
	public List<Payoutlist> findUserIncomeByPage(Integer page, Integer size,Integer uid) {
		String queryString;
		Query q ;
		try {
			 queryString = "from Payoutlist msg where msg.account.aid = "+uid+" and success !=3 and success !=4 order by msg.ptime desc";
			 q = getCurrentSession().createQuery(queryString);
			q.setFirstResult(page*size);
			q.setMaxResults(size);
			return q.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	
}